//
//  AuthViewController.swift
//  SinaWeibo
//
//  Created by 王鹏 on 16/4/15.
//  Copyright © 2016年 heihei. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class AuthViewController: UIViewController {

    let webView = UIWebView()
    let redirect_uri = "http://www.baidu.com"
    let client_id =  "3908447282"
    
    //监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fullAccount() {
        let jsStr = "document.getElementById('userId').value = '371502526@qq.com' , document.getElementById('passwd').value = 'wangpeng'"
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
    
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        //加载网页
        loadOauthPage()
    }
    
    private func loadOauthPage() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "3908447282" + "&redirect_uri=" + "http://www.baidu.com"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setupUI() {
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
    
}




extension AuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    /*
    Optional(https://api.weibo.com/oauth2/authorize?client_id=3908447282&redirect_uri=http://www.baidu.com)
    Optional(https://api.weibo.com/oauth2/authorize)
    Optional(https://api.weibo.com/oauth2/authorize#)
    Optional(https://api.weibo.com/oauth2/authorize)
    Optional(http://www.baidu.com/?code=6ddce28d767c949b4e4ed6378838d738)
    Optional(https://m.baidu.com/?code=6ddce28d767c949b4e4ed6378838d738&from=844b&vit=fps)
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //每一个请求中的url
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //都是授权界面  所以允许通过
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        
        //不包含回调页的请求全都不通过
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        //query包含了url中的所有参数和值
        let query = request.URL?.query
        
        let codestr = "code="
        let code = query!.substringFromIndex(codestr.endIndex)
        
        loadAccessToken(code)
        
        return false
    }
    //网页的代理方法(一共四个 这是最后一个)
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    private func loadAccessToken(code: String) {
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let urlstr = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id, "client_secret" : "5ed7d2e56e0267ae38d9588a44ff4df8" , "code" : code , "grant_type" : "authorization_code" , "redirect_uri" : redirect_uri]
        
        AFN.POST(urlstr, parameters: parameters, success: { (_, result) -> Void in

            if let dict = result as? [String : AnyObject] {
                
                //开始字典转模型
                let account = UserAccount(dict: dict)
                //相信客户端一定能给的数据一定能够取到  所以加上 ! 这样就一定有值
                self.loadUserInfo(account)
                print(account)
                
            }
            
            
            }) { (_, error) -> Void in
                print(error)
                
        }
        
        
    }
    
    private func loadUserInfo(account: UserAccount) {
        let urlstring = "https://api.weibo.com/2/users/show.json"
        let parmaters = ["access_token" : account.access_token! , "uid" : account.uid!]
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlstring, parameters: parmaters, success: { (_, result) -> Void in
           if let dict = result as? [String : AnyObject] {
             account.avatar_large = dict["avatar_large"] as? String
            account.name = dict["name"] as? String
            account.saveAccount()
            let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
            print(path)
            }
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    
    
    
    
}

